package com.srolorz.fmtp.thread.pool.executor.pool;

import com.srolorz.fmtp.thread.pool.executor.event.ThreadPoolEvent;
import com.srolorz.fmtp.thread.pool.executor.factory.ThreadPoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author eleven
 */
public class ThreadPoolService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolService.class);
    private static ReentrantLock lock = new ReentrantLock();
    private static ThreadPoolService threadPoolService;

    public void execute(ThreadPoolEvent event) {
        if(null == event){
            LOGGER.info("thread event can not be null!！");
            return;
        }

        ThreadPoolExecutor threadExecutor = ThreadPoolFactory.getThreadExecutor(event.getThreadGroupName());
        threadExecutor.execute(() -> {
            event.doing();
            event.executeEvent();
        });
    }

    public FutureTask submit(ThreadPoolEvent event) {
        if(null == event){
            LOGGER.info("thread event can not be null!！");
            return null;
        }

        ThreadPoolExecutor threadExecutor = ThreadPoolFactory.getThreadExecutor(event.getThreadGroupName());
        ThreadCallable threadCallable = new ThreadCallable(event);
        FutureTask futureTask = new FutureTask(threadCallable);
        threadExecutor.submit(futureTask);
        return futureTask;
    }

    public static ThreadPoolService build() {
        return Single.NEW_INSTANCE;
    }

    private static final class Single {
        private static final ThreadPoolService NEW_INSTANCE = new ThreadPoolService();
    }

}
